import 'package:flutter/material.dart';
import '../../../widget/PPBaseWidget.dart';
import 'package:url_launcher/url_launcher.dart';

import './widget/PPSwiperView.dart';
import './widget/PPRowImageView.dart';
import './widget/PPRowWrapView.dart';
import './widget/PPTitleAndDescHeadView.dart';
import './widget/PPHorizontalScrollView.dart';
import './widget/PPHorizontalScrollTabView.dart';
import './widget/PPCommdityColumnView.dart';
import '../../../widget/PPLoading.dart';

import './presenter/PPShopHomePresenter.dart';
import './model/PPShopHomePageModel.dart';




class PPShopHomePage extends StatefulWidget with PPBaseWidget {

    PPShopHomePage({Key key, this.title}) : super(key: key);

    final String title;

    _PPShopHomePageState createState() => _PPShopHomePageState();
}

class _PPShopHomePageState extends State <PPShopHomePage> {

    PPShopHomePresenter presenter = new PPShopHomePresenter();

    ScrollController _scrollController = ScrollController();

    PPLoading loading;

    List<PPShopPlate> plateItems = [];


    // 构造函数
    _PPShopHomePageState() {
        print('构造函数');
    }

    // 初始化一些数据
    @override
    void initState() {
        super.initState();

        print("initState");
    }

    @override
    void didChangeDependencies() {
        super.didChangeDependencies();
        print("didChangeDependencies");
        if(loading != null){
            loading.show();
        }
        _requestShopHomePlateInfo();
    }

    // 组件状态改变时候调用，可能会调用多次
    @override
    void didUpdateWidget(PPShopHomePage oldWidget) {
        super.didUpdateWidget(oldWidget);
        print("didUpdateWidget");
    }

    // 当State对象从树中被移除时，会调用此回调。
    @override
    void deactivate() {
        super.deactivate();
    }

    // 当State对象从树中被永久移除时调用；通常在此回调中释放资源。
    void dispose() {
        super.dispose();
        print("dispose");
    }

    // 绘制界面  调用次数
    @override
    Widget build(BuildContext context) {
        if(loading == null) {
            loading = PPLoading(context);
        }
        print("build");
        return Scaffold(
            appBar: AppBar(
                title: Text(widget.title),
                actions: [
                    IconButton(
                    icon: Icon(Icons.linked_camera),
                    onPressed: _onClickRightNavButtonAction,
                    )
                ],
            ),
            body: RefreshIndicator(
                onRefresh: _onRefreshAction,
                child: ListView.builder(
                    itemCount: plateItems.length,
                    itemBuilder: _buildListItems,
                    controller: _scrollController,
                )
            ) 
        );
    }
    
    Widget _buildListItems(BuildContext context, int index) {
        PPShopPlate item = plateItems[index];
        String plateHStr = item.plateHeight == null ? '0' : item.plateHeight.toString();
        double plateHeight = double.parse(plateHStr);
        double relateH = widget.getReleateheight(context, plateHeight);
        List<PPShopPlateContent> contentList = item.contentList;
        switch(item.plateType) {
            case '01': {
                return (PPSwiperView(contentList, h: relateH, onPressAction: _onClickSwiperItemAction));
            }
            case '02': {
                return (PPRowImageView(contentList, h: relateH, onPressAction: _onPressRowImageItemAction));
            }
            case '03': {
                return (PPRowWrapView(contentList, onPressItemAction: _onPressRowWrapItemAction));
            }
            case '05': {
                List<PPCommodityModel> cmmdtyList = item.cmmdtyList;
                Map<String, List<PPCommodityModel>> columnData = _getCommodityColumns(cmmdtyList);
                return (Column(
                    children: <Widget>[
                        PPHorizontalScrollTabView(contentList, changeSelectTab: _onPressChangeSelectTabItem),
                        PPCommdityColumnView(columnData, onPressAction: _onPressCommodityItemAction)
                    ],
                ));
            }
            case '07': {
                String plateName = item.plateName;
                String contentDesc = contentList != null && contentList.length > 0 ? contentList[0].contentDesc : null;
                String redirectUrl = contentList != null && contentList.length > 0 ? contentList[0].redirectUrl : null;
                return (PPTitleAndDescHeadView(plateName, desc: contentDesc, redirectUrl: redirectUrl, onPressAction: _onPressTitleHeadAction));
            }
            case '08': {
                String plateName = item.plateName;
                String contentDesc = contentList != null && contentList.length > 0 ? contentList[0].contentDesc : null;
                String redirectUrl = contentList != null && contentList.length > 0 ? contentList[0].redirectUrl : null;
                return (PPTitleAndDescHeadView(plateName, desc: contentDesc, redirectUrl: redirectUrl, onPressAction: _onPressTitleHeadAction));
            }
            case '09': {
                String plateName = item.plateName;
                String contentDesc = contentList != null && contentList.length > 0 ? contentList[0].contentDesc : null;
                String redirectUrl = contentList != null && contentList.length > 0 ? contentList[0].redirectUrl : null;
                return (PPTitleAndDescHeadView(plateName, desc: contentDesc, redirectUrl: redirectUrl, onPressAction: _onPressTitleHeadAction));
            }
            default: return Container();
        }
    }

    Map<String, List<PPCommodityModel>> _getCommodityColumns(List<PPCommodityModel>list) {
        List<PPCommodityModel> leftColumn = [];
        List<PPCommodityModel> rightColumn = [];
        if(list != null) {
            for (PPCommodityModel item in list) {
                int index = list.indexOf(item);
                if(index % 2 == 0) {
                    leftColumn.add(item);
                } else {
                    rightColumn.add(item);
                }
            }
        } 
        return { "leftColumn": leftColumn, "rightColumn": rightColumn };
    }

    // 下拉刷新
    Future<Null> _onRefreshAction() async {
        _requestShopHomePlateInfo();
    }

    // 点击navbar 的 right action
    _onClickRightNavButtonAction() {
        Navigator.pushNamed(context, widget.ppRoutesPath["PPInterestOptionsPage"]);
    }

    // 点击轮播图
    _onClickSwiperItemAction(int index) {
        if(index == 0) {
            Navigator.pushNamed(context, '/personal'); 
        } else {
            Navigator.pushNamed(context, '/aaa'); 
        }
    }

    //点击按行进行wrap排列的item
    _onPressRowWrapItemAction(PPShopPlateContent data, int index) {
        Navigator.pushNamed(context, '/shop/commodity/detail');
    }

    // 点击屏幕宽度的单张图片
    _onPressRowImageItemAction(PPShopPlateContent data, int index) {
        String redirectUrl = data.redirectUrl;
        if(redirectUrl != null && redirectUrl.length > 0) {
            launch(redirectUrl);
        }
    }

    //点击描述文字head
    _onPressTitleHeadAction(String title, String redirectUrl) {
        if(redirectUrl != null && redirectUrl.length > 0) {
            launch(redirectUrl);
        }
    }

    // 点击水平滑动的商品item
    _onPressRowScrollItemAction(PPCommodityModel data, int index) {
        if(index == 0) {
            presenter.requestShopHomePlateInfo((bool isSucceed, Map result, String msg){

            });
        } else if(index == 1) {
            presenter.requestFirstPageCmmdtyList((bool isSucceed, Map result, String msg){

            });
        } else if(index == 2) {

        }  
    }
    
    // 点击水平滑动tab切换的组件
    _onPressChangeSelectTabItem(PPShopPlateContent data, int index) {
        presenter.selTabItem = data;
        loading.show();
        _requestShopHomeCmmdtyList();
    }

    // 点击商品item
    _onPressCommodityItemAction(PPCommodityModel item) {
        Navigator.pushNamed(context, widget.ppRoutesPath["PPCommodityDetailPage"], arguments: {'id': item.cmmdtyCode}); 
    }

    _requestShopHomePlateInfo() {
        presenter.requestShopHomePlateInfo((bool isSucceed, List<PPShopPlate> models, String msg){
            if(isSucceed) {
                setState(() {
                    plateItems = models;
                });
                _requestShopHomeCmmdtyList();
            } else {
                print("error ==== " + msg);
            }
        });
    }

    _requestShopHomeCmmdtyList() {
        presenter.requestFirstPageCmmdtyList((bool isSucceed, List<PPShopPlate> models, String msg){
            loading.close();
            if(isSucceed) {
                setState(() {
                    plateItems = models;
                });
            } else {
                print("error ==== " + msg);
            }
        });
     }
    
}
